package com.cn.ycy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.jayway.jsonpath.JsonPath;
import com.cn.ycy.utils.HttpRequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

@Service
public class AccessTokenOpenapiServiceImpl {

  Logger logger = LoggerFactory.getLogger(AccessTokenOpenapiServiceImpl.class);

  @ApolloConfig
  private Config apolloConfig;

  public static final String OPENAPI_REQUESTTEMPLATE = "openapi.requesttemplate";

  public static final String NO_CHANNEL_TYPE_REQUEST_TEMPLATE = "channelType没有对应的requestTemplate";

  public static final String NO_RESPONSE = "no response";
  public static final String NO_ExpireTime = "need expireTime";

  @PostConstruct
  public void doc() {

//    new Thread(new Runnable() {
//      @Override
//      public void run() {
//        while (true) {
//          String property = apolloConfig.getProperty(OPENAPI_REQUESTTEMPLATE + "wechat", "");
//          logger.warn(property);
//          try {
//            TimeUnit.SECONDS.sleep(5);
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }
//        }
//      }
//    }).start();
  }

  public AccessTokenRes getTokenAccess(String channelType, String reqestJson) {
    AccessTokenRes accessTokenRes = new AccessTokenRes();
    accessTokenRes.status = 2;
    //获取请求模版
    String requestTempleteStr = apolloConfig.getProperty(OPENAPI_REQUESTTEMPLATE + channelType.toLowerCase(), "");
    RequestTemplete requestTemplete = null;
    if (StringUtils.isNotBlank(requestTempleteStr)) {
      requestTemplete = JSON.parseObject(requestTempleteStr, RequestTemplete.class);
    } else {
      accessTokenRes.msg = NO_CHANNEL_TYPE_REQUEST_TEMPLATE;
      return accessTokenRes;
    }

    String res = null;
    //访问外部接口
    try {
      res = callOpenApi(requestTemplete.requesturl, requestTemplete.requestmethod, reqestJson);
    } catch (Exception e) {
      accessTokenRes.msg = e.getMessage();
      return accessTokenRes;
    }

    //没有消息体
    if (StringUtils.isBlank(res)) {
      accessTokenRes.msg = NO_RESPONSE;
      return accessTokenRes;
    }

    //解析 token
    try {
      accessTokenRes.token = JsonPath.read(res, "$." + requestTemplete.responsebodyTokenath);
    } catch (Exception e) {
      accessTokenRes.msg = e.getMessage();
      return accessTokenRes;
    }

    //解析 token生命周期
    if (requestTemplete.responsebodyDefaultxpiretime > 0) {
      accessTokenRes.expireTime = requestTemplete.responsebodyDefaultxpiretime;
    } else if (StringUtils.isNotBlank(requestTemplete.responsebodyExpiretimePath)) {
      try {
        accessTokenRes.expireTime =
                JsonPath.read(res, "$." + requestTemplete.responsebodyExpiretimePath);
      } catch (Exception e) {
        accessTokenRes.msg = e.getMessage();
        return accessTokenRes;
      }
    } else {
      //需要一个指定的token生命周期
      accessTokenRes.msg = NO_ExpireTime;
      return accessTokenRes;
    }
    //成功
    accessTokenRes.status = 1;
    return accessTokenRes;
  }


  protected String callOpenApi(String requestUrl, String requestMethod, String requestJson) {
    int reTrytimes = 2;
    if ("post".equalsIgnoreCase(requestMethod))
      return HttpRequestUtils.doPostCanRetry(requestUrl, requestJson, reTrytimes);
    Map header = JSONObject.parseObject(requestJson, Map.class);
    return HttpRequestUtils.doGetCanRetry(requestUrl, header, reTrytimes);
  }

}
